import 'package:flutter/material.dart';
import '../services/location_service.dart';
import '../services/weather_service.dart';
import '../utils/storage_util.dart';

class LocationWeatherProvider with ChangeNotifier {
  final LocationService _locationService = LocationService();
  final WeatherService _weatherService = WeatherService();

  String _currentAddress = '正在定位...';
  int _temperature = 22;
  String _weatherDescription = '晴';
  String _weatherIcon = '☀️';
  bool _isLoading = true;
  bool _hasError = false;

  // Getters
  String get currentAddress => _currentAddress;
  int get temperature => _temperature;
  String get weatherDescription => _weatherDescription;
  String get weatherIcon => _weatherIcon;
  bool get isLoading => _isLoading;
  bool get hasError => _hasError;

  /// 初始化位置和天气信息
  Future<void> initializeLocationAndWeather() async {
    _isLoading = true;
    _hasError = false;
    notifyListeners();

    try {
      // 首先检查是否有缓存的位置信息
      final hasCache = await StorageUtil.hasLocationCache();
      
      if (hasCache) {
        // 使用缓存的信息
        final cachedLocation = await StorageUtil.getCachedLocation();
        final cachedWeather = await StorageUtil.getCachedWeather();
        
        if (cachedLocation != null && cachedWeather != null) {
          _currentAddress = cachedLocation;
          _temperature = cachedWeather['temperature'];
          _weatherDescription = cachedWeather['description'];
          _weatherIcon = cachedWeather['icon'];
          _isLoading = false;
          notifyListeners();
          return;
        }
      }

      // 没有缓存或缓存无效，重新获取位置信息
      final locationInfo = await _locationService.getCurrentLocationInfo();
      
      if (locationInfo['success']) {
        _currentAddress = locationInfo['address'];
        
        // 获取天气信息
        final weatherInfo = await _weatherService.getWeatherByCoordinates(
          locationInfo['latitude'],
          locationInfo['longitude'],
        );
        
        if (weatherInfo['success']) {
          _temperature = weatherInfo['temperature'];
          _weatherDescription = weatherInfo['description'];
          _weatherIcon = weatherInfo['icon'];
        } else {
          // 使用默认天气信息
          _setDefaultWeather();
        }

        // 保存到缓存
        await StorageUtil.saveLocationWeather(
          address: _currentAddress,
          temperature: _temperature,
          weatherDescription: _weatherDescription,
          weatherIcon: _weatherIcon,
        );
        notifyListeners();
      } else {
        // 定位失败，使用广州番禺区默认坐标
        _currentAddress = '广州市番禺区';
        
        // 使用番禺区坐标获取天气
        final weatherInfo = await _weatherService.getWeatherByCoordinates(22.9375, 113.3642);
        
        if (weatherInfo['success']) {
          _temperature = weatherInfo['temperature'];
          _weatherDescription = weatherInfo['description'];
          _weatherIcon = weatherInfo['icon'];
        } else {
          _setDefaultWeather();
        }
        
        // 保存到缓存
        await StorageUtil.saveLocationWeather(
          address: _currentAddress,
          temperature: _temperature,
          weatherDescription: _weatherDescription,
          weatherIcon: _weatherIcon,
        );
      }
    } catch (e) {
      _hasError = true;
      _currentAddress = '位置获取失败';
      _setDefaultWeather();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 刷新位置和天气信息（强制重新获取）
  Future<void> refreshLocationAndWeather() async {
    // 清除缓存，强制重新获取
    await StorageUtil.clearLocationWeatherCache();
    await initializeLocationAndWeather();
  }

  /// 清除位置和天气缓存（退出app时调用）
  Future<void> clearLocationWeatherCache() async {
    await StorageUtil.clearLocationWeatherCache();
  }

  /// 设置默认天气信息
  void _setDefaultWeather() {
    _temperature = 22;
    _weatherDescription = '晴';
    _weatherIcon = '☀️';
  }

  /// 手动设置位置（用于测试或用户手动选择）
  void setManualLocation(String address) {
    _currentAddress = address;
    notifyListeners();
  }

  /// 根据城市名获取天气
  Future<void> getWeatherByCity(String cityName) async {
    try {
      final weatherInfo = await _weatherService.getWeatherByCity(cityName);
      
      if (weatherInfo['success']) {
        _temperature = weatherInfo['temperature'];
        _weatherDescription = weatherInfo['description'];
        _weatherIcon = weatherInfo['icon'];
        _hasError = false;
      } else {
        _hasError = true;
        _setDefaultWeather();
      }
      
      notifyListeners();
    } catch (e) {
      _hasError = true;
      _setDefaultWeather();
      notifyListeners();
    }
  }
}